package handler

import (
	"context"
	"errors"
	pb "mpps/services/srv-UserRegister/proto"
	common "mpps/tools/common"
	"mpps/tools/repository/dao"
	"mpps/tools/repository/dao/user"
)

type UserRegister struct {
}

func NewUserRegister() *UserRegister {
	return &UserRegister{}
}

// Call is a single request handler called via client.Call or the generated client code
func (c *UserRegister) Call(ctx context.Context, req *pb.Request, rsp *pb.Response) error {
	if len(req.Email) <= 0 || len(req.Password) < 6 {
		return errors.New(common.ErrParamsValidation.Message)
	}
	if !common.IsEmail(req.Email) {
		return errors.New(common.ErrParamsValidation.Message)
	}
	model := user.User{
		Email:    req.Email,
		Password: req.Password,
	}

	model.UserId = common.Md5(model.Email)
	model.Password = common.Md5(model.Password)
	model.Version = "1.0.0"

	result := dao.GetDB(ctx).Model(&user.User{}).Create(&model)
	if result.RowsAffected > 0 {
		rsp.Code = int32(common.OK.Code)
		rsp.Msg = common.OK.Message
	} else {
		return errors.New(common.ErrPostCreateUser.Message)
	}
	return nil
}
